//
//  TextView+Extension.swift
//  IMIHome
//
//  Created by Roffa Zhou on 2021/9/8.
//  Copyright © 2021 上海创米科技有限公司. All rights reserved.
//

import Foundation
import SnapKit

public extension UITextView {
    public enum RFTextViewType{
        case begin      //开始编辑
        case end        //结束编辑
    }
    private struct AssociatedKey{
        static var closureKey = "textviewClosure"
    }
    
    public var closure: ((RFTextViewType)->Void)?{
        get {
            let c = objc_getAssociatedObject(self, &AssociatedKey.closureKey) as! ((RFTextViewType) -> Void)?
            return c
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.closureKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
    }
    func placeHolder(_ str: String, color: UIColor = UIColor.hexColor(0xb2b2b2)){
        if self.viewWithTag(2021090800) == nil {
            let lbl = UILabel()
            lbl.tag = 2021090800
            addSubview(lbl)
            lbl.snp.makeConstraints { make in
                make.width.height.equalToSuperview()
                make.left.top.equalTo(0)
            }
            lbl.font = self.font
            lbl.textColor = color
            lbl.text = str
            if !text.isEmpty {
                lbl.isHidden = true
                return
            }
        }
        
    }
    /**简单通过响应链解耦实现textfield键盘出现后，位置调整*/
    @discardableResult
    func listen() -> UITextView{
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        return self
    }
    
    /// 找到当前textfield所在的viewcontroller.view的一级子视图
    /// - Returns: 返回找到的视图
    private func frameView()->UIView{
        var view = self.superview
        while view != nil, view?.superview != self.viewController?.view {
            view = view!.superview
        }
        return view!
    }
    
    @objc private func keyboardWillShow(_ notification: Notification) {
        let rect = notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        let placeHolder = self.viewWithTag(2021090800)
        if placeHolder != nil {
            placeHolder!.isHidden = true
        }

        if self.viewController?.view.viewWithTag(2021090700) == nil {  //增加一层遮罩
            let coverView = UIView()
            coverView.tag = 2021090700
            self.viewController!.view.addSubview(coverView)
            coverView.isUserInteractionEnabled = true
            coverView.snp.makeConstraints { make in
                make.left.top.right.equalTo(0)
                make.bottom.equalTo(self.snp.top)
            }
            coverView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closeKeyboard)))
        }
        self.frameView().transform = CGAffineTransform.identity

        UIView.animate(withDuration: 0.3) {
            self.frameView().transform = CGAffineTransform(translationX: 0, y: self.viewController!.view.height - self.frameView().maxY - rect.height - 10)
        }completion: { result in
            self.closure?(.begin)
        }
    }

    @objc private func keyboardWillHide(_ notification: Notification) {
        let placeHolder = self.viewWithTag(2021090800)
        if placeHolder != nil, text.isEmpty {
            placeHolder!.isHidden = false
        }
        UIView.animate(withDuration: 0.3) {
            self.frameView().transform = CGAffineTransform.identity
        }completion: { b in
            self.closure?(.end)
        }
        removeCoverView()
    }
    
    @objc private func closeKeyboard(){
        resignFirstResponder()
        removeCoverView()
    }
    private func removeCoverView(){
        let view = self.viewController?.view.viewWithTag(2021090700)
        if view != nil {
            view!.removeFromSuperview()
        }
    }
    
    /// 获取当前输入字符数，去除被选中部分
    /// - Returns: 返回当前输入数
    /// - Authors: rf/2021-10-25
    public func inputCount() -> Int{
        var count = text.count
        if markedTextRange != nil {
            let markedCount = offset(from: markedTextRange!.start, to: markedTextRange!.end)
            if count > markedCount {
                count -= markedCount
            }
        }
        return count
    }
}
